package com.springboot.demo.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.demo.entity.IncomeRecord;
import com.springboot.demo.service.IncomeRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springboot.demo.entity.Reader;
import com.springboot.demo.dao.ReaderDao;

import static java.lang.Integer.parseInt;

@Controller
public class LibrarianChangeInfoController {

    @Autowired
    private ReaderDao readerDao;

    @Autowired
    private IncomeRecordService incomeRecordService;

    /**
     * 1、进入增删改查界面
     * @return
     */
    @RequestMapping("/librarian_Changeinfo_Reader")
    public String librarian_Changeinfo_Reader() {
        return "librarian_Changeinfo_Reader";
    }

    /**
     * 2、显示
     * @param page
     * @param rows
     * @return
     */
    @ResponseBody
    @RequestMapping("/librarian_reader_list")
    public Map<String, Object> list(Reader reader,
                                    @RequestParam(value = "page", required = false) Integer page,
                                    @RequestParam(value = "rows", required = false) Integer rows
    ) {
        Pageable pageable = PageRequest.of(page-1, rows, Sort.Direction.ASC, "phone");
        Page<Reader> pageReader = readerDao.findAll(new Specification<Reader>() {

            @Override
            public Predicate toPredicate(Root<Reader> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // TODO Auto-generated method stub
                Predicate predicate = cb.conjunction();
                if(reader!=null){
                    if(reader.getPhone()!=null){
                        predicate.getExpressions().add(cb.like(root.get("phone"),"%"+reader.getPhone()+"%"));
                    }
                    if(reader.getRname()!=null){
                        predicate.getExpressions().add(cb.like(root.get("rname"),"%"+reader.getRname().trim()+"%"));
                    }
                }
                return predicate;
            }

        }, pageable);
        // ①获取rows
        List<Reader> list = pageReader.getContent();
        // ②获取count
        Long count = readerDao.count(new Specification<Reader>() {

            @Override
            public Predicate toPredicate(Root<Reader> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // TODO Auto-generated method stub
                Predicate predicate = cb.conjunction();
                if(reader!=null){
                   if(reader.getPhone()!=null){
                        predicate.getExpressions().add(cb.like(root.get("phone"),"%"+reader.getPhone()+"%"));
                    }
                    if(reader.getRname()!=null){
                        predicate.getExpressions().add(cb.like(root.get("rname"),"%"+reader.getRname().trim()+"%"));
                    }
                }
                return predicate;
            }

        });
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("rows", list);
        resultMap.put("total", count);
        resultMap.put("success", true);
        return resultMap;
    }

    /**
     * 3、添加、修改
     * @param reader
     * @return
     */
    @ResponseBody
    @RequestMapping("/librarian_reader_save")
    public Map<String, Object> save(Reader reader) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        readerDao.save(reader);

        //判断是否已经数据库中存在该记录
        QueryWrapper<IncomeRecord> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.eq("category","earnest_money");
        recordQueryWrapper.eq("phone",reader.getPhone());
        IncomeRecord queryRecord = incomeRecordService.getOne(recordQueryWrapper);
        //增加图书馆的收入记录---保证金收入
        if(queryRecord == null && reader.getRegister().equals("yes")){
            IncomeRecord incomeRecord = new IncomeRecord();
            incomeRecord.setPhone(reader.getPhone());
            incomeRecord.setCategory("earnest_money");
            incomeRecord.setMoney(reader.getDeposit());
            incomeRecord.setDate(new Date());
            incomeRecordService.save(incomeRecord);
        }

        resultMap.put("success", true);
        return resultMap;
    }

    /**
     * 4、删除
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/librarian_reader_delete")
    public Map<String, Object> delete(@RequestParam(value = "ids") String ids) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String[] idsStr = ids.split(",");
        //for (int i = 0; i < ids.length; i++) {
       for (String i:idsStr) {
           readerDao.deleteById(i);
       }

        resultMap.put("success", true);
        return resultMap;
    }

}
